package com.jfinal.j2cache.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TokenReplaceTextManipulator {

	private String startToken = "[";
	private String endToken = "]";
	private String nullValue = "";

	public TokenReplaceTextManipulator(String startToken, String endToken, String nullValue) {
		this.startToken = startToken;
		this.endToken   = endToken;
		this.nullValue  = nullValue;
	}

	TokenReplaceTextManipulator() {

	}

	public StringBuffer manipulate(StringBuffer text, Map<String, Object> model) {
		if (model == null) {
			return text;
		}

		int i = 0;
		int start;
		for (int end = 0; (start = text.toString().indexOf(this.startToken, end)) >= 0; i++) {
			end = text.toString().indexOf(this.endToken, start);
			String key = text.substring(start + this.startToken.length(), end);

			Object modelValue = model.get(key);
			text.replace(start, end + 1, modelValue == null ? this.nullValue
					: modelValue.toString());
			end -= key.length() + 2;
		}

		return text;
	}

	public List<String> getKeys(StringBuffer text) {
		List<String> keys = new ArrayList<String>();

		int i = 0;
		int start;
		for (int end = 0; (start = text.toString().indexOf(this.startToken, end)) >= 0; i++) {
			end = text.toString().indexOf(this.endToken, start);
			String key = text.substring(start + this.startToken.length(), end);

			keys.add(key);

			text.replace(start, end + 1, "");
			end -= key.length() + 2;
		}

		return keys;
	}

	public String manipulate(String source, Map<String, Object> model) {
		return manipulate(new StringBuffer(source), model).toString();
	}
}